package com.atguigu.srb.gateway.filter;


import com.atguigu.srb.common.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Component
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("拦截所有请求");

        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径
        URI uri = request.getURI();

        // 获取请求路径
        RequestPath path = request.getPath();

        // 获取请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        System.out.println("请求鉴权");

        // 获取请求头中的token
        List<String> tokens = request.getHeaders().get("token");
        System.out.println("获取请求头中的token:" + tokens);

        // 判断token是否存在
        if (null != tokens && tokens.size() > 0) {
            String token = tokens.get(0);
            System.out.println("需要进行鉴权的token:" + token);
            // 验证token
            boolean b = JwtUtils.checkToken(token);
            if (b) {
                // 鉴权成功，将用户id传递给微服务
                Long userId = JwtUtils.getUserId(token);
                // 将用户id放入请求头中
                request.mutate().header("userId", userId.toString());
                // 将请求头放入exchange中
                exchange.mutate().request(request);
            } else {
                // 鉴权失败，返回错误信息
                System.out.println("鉴权失败");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
        // 放行
        return chain.filter(exchange);
    }
}
